package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.*;
import com.itheima.service.AddressService;
import com.itheima.service.MemberService;
import com.itheima.service.SetmealService;
import com.itheima.utils.DateUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/member/First")
public class MemberController {

    @Reference
    private MemberService memberService;
    @Reference
    private AddressService addressService;
    @Reference
    private SetmealService setmealService;

    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) throws Exception {
        return memberService.findPage(queryPageBean);
    }

    @RequestMapping("/findById")
    public Result findById(Integer id) {
        try {
            Member member = memberService.findById(id);
            return new Result(true, MessageConstant.GET_MEMBER_SUCCESS, member);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_MEMBER_FAIL);
        }
    }

    @RequestMapping("/edit")
    public Result edit(@RequestBody Member member) {
        try {
            memberService.edit(member);
            return new Result(true, MessageConstant.EDIT_MEMBERANDHEALTH_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_MEMBERANDHEALTH_FAIL);
        }
    }

    @RequestMapping("/add")
    public Result add(@RequestBody Member member) {
        try {
            member.setRegTime(DateUtils.parseDate2String(new Date()));
            memberService.addMember(member);
            return new Result(true, MessageConstant.ADD_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_MEMBER_FAIL);
        }
    }

    @RequestMapping("/delete")
    public Result delete(Integer id) {
        try {
            boolean flag = memberService.deleteMember(id);
            if (flag) {
                return new Result(true, MessageConstant.DELETE_MEMBER_SUCCESS);
            }
            return new Result(false, MessageConstant.DELETE_MEMBERANDHEALTH_FORFAIL);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.DELETE_MEMBER_FAIL);
        }
    }

    @RequestMapping("/export")
    public Result export2Excel(Integer[] ids, HttpServletRequest request, HttpServletResponse response) {
        try {
            //动态获取模板文件在磁盘的路径
            String filePath = request.getSession().getServletContext().getRealPath("template") + File.separator + "memberDetail_template.xlsx";
            //基于提供的Excel模板文件在内存中创建一个Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File(filePath)));
            //读取第一个工作表
            XSSFSheet sheet = excel.getSheetAt(0);
            //设置初始填充数据的行
            int rowNum = 1;
            //遍历会员id,分别获取对应的会员信息,进行导出填充到excle中
            for (int i = 0; i < ids.length; i++) {
                Member member = memberService.findById(ids[i]);
                //读取第二行
                XSSFRow row = sheet.getRow(rowNum);
                rowNum++;
                //设置每次都从第一列开始填充数据
                int colNum = 0;
                //向表格中填充序号
                XSSFCell cell = row.createCell(colNum);

                cell.setCellValue(i + 1);

                //填充会员姓名
                if (member.getName() != null) {
                    row.createCell(++colNum).setCellValue(member.getName());
                } else {
                    row.createCell(++colNum).setCellValue("");
                }

                //填充会员性别
                if (member.getSex() != null) {
                    if ("1".equals(member.getSex())) {
                        row.createCell(++colNum).setCellValue("男");
                    } else {
                        row.createCell(++colNum).setCellValue("女");
                    }
                } else {
                    row.createCell(++colNum).setCellValue("");
                }

                //填充会员出生日期
                if (member.getBirthday() != null) {
                    row.createCell(++colNum).setCellValue(DateUtils.parseDate2String(member.getBirthday()));
                } else {
                    row.createCell(++colNum).setCellValue("");
                }

                //填充手机号
                if (member.getPhoneNumber() != null) {
                    row.createCell(++colNum).setCellValue(member.getPhoneNumber());
                } else {
                    row.createCell(++colNum).setCellValue("");
                }

                //填充体检机构和体检机构的详细地址
                Address address = addressService.getByMemberId(ids[i]);
                if (address != null && address.getAddressName() != null) {
                    row.createCell(++colNum).setCellValue(address.getAddressName());
                } else {
                    row.createCell(++colNum).setCellValue("");
                }
                if (address != null && address.getDetailaddress() != null) {
                    row.createCell(++colNum).setCellValue(address.getDetailaddress());
                } else {
                    row.createCell(++colNum).setCellValue("");
                }

                //获取会员对应的体检套餐填充到表格中
                List<Setmeal> setmealLsit = memberService.findSetmealName(ids[i]);
                Setmeal setmeal = setmealLsit.get(0);
                if (setmealLsit != null && setmeal != null) {
                    row.createCell(++colNum).setCellValue(setmeal.getName());

                //获取会员的体检套餐对应的检查组和检查项
                List<CheckGroup> checkGroupList = memberService.findCheckGroup(setmeal.getId());

                if (checkGroupList != null) {
                    StringBuilder checkGroupName = new StringBuilder();
                    for (int j = 0; j < checkGroupList.size(); j++) {
                        checkGroupName.append(j == checkGroupList.size() - 1 ?
                                checkGroupList.get(j).getName() : checkGroupList.get(j).getName() +",");
                    }
                    //填充检查组到表格中
                    row.createCell(++colNum).setCellValue(checkGroupName.toString());
                    //获取会员体检套餐的检查组对应关联的所有检查项填充到表格中
                    StringBuilder checkGroupAndCheckItem = new StringBuilder();
                    for (int k = 0; k < checkGroupList.size(); k++) {
                        List<CheckItem> checkItemList = memberService.findCheckItemByCheckGroupId(checkGroupList.get(k).getId());
                        if (checkItemList != null) {
                            StringBuilder checkItem = new StringBuilder("[");
                            for (int m = 0; m < checkItemList.size(); m++) {
                                checkItem.append(m == checkItemList.size() - 1 ? checkItemList.get(m).getName() + "]" : checkItemList.get(m).getName() + ",");
                            }
                            checkGroupAndCheckItem.append(k == checkGroupList.size() - 1 ? checkItem.toString() : checkItem + ",");
                        } else {
                            row.createCell(colNum).setCellValue("");
                        }
                        //填充数据到表格中
                        row.createCell(colNum).setCellValue(checkGroupAndCheckItem.toString());
                    }
                } else {
                    row.createCell(colNum).setCellValue("");
                }
            }else {
                    row.createCell(colNum).setCellValue("");
                }
            }

            //使用输出流进行表格下载,基于浏览器作为客户端下载
            OutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");//代表的是Excel文件类型
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");//指定以附件形式进行下载
            excel.write(out);
            //释放资源
            out.flush();
            out.close();
            excel.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_MEMBER_REPORT_FAIL);
        }
    }

}
